import { Component } from '@angular/core';
import { NzModalService, NzModalRef, NzNotificationService } from 'ng-zorro-antd';
import { ApiService } from '@srvs/api.service';

import { EditBaseTypeKeysComponent } from './edit-base-type-keys/edit-base-type-keys.component';
import { EditBaseTypeValuesComponent } from './edit-base-type-values/edit-base-type-values.component';

@Component({
  selector: 'base-type-management',
  templateUrl: './base-type-management.component.html',
  styleUrls: ['./base-type-management.component.less']
})
export class BaseTypeManagementComponent {

  public config: any = {
    valuesLoading: false
  };
  public data: any = {
    keys: [],
    values: []
  };
  public params: any = {
    keywords: null,
    key: null
  }
  private currentKeyTools: Element;
  private debounce: any;

  constructor(
    private modalSrv: NzModalService,
    private msgSrv: NzNotificationService,
    private apiSrv: ApiService,
  ) {
    this.load();
  }

  /**
   * 加载基本类型键
   */
  public load(): void {
    const apiKeys: string = this.params.keywords
      ? `/api/_search/base-type-keys?query="${this.params.keywords}"`
      : '/api/base-type-keys';
    this.apiSrv.get(apiKeys).subscribe(
      data => {
        this.data.keys = data;
        if (data.length) {
          this.changeKey(data[0]);
        } else {
          this.data.values = [];
          this.params.key = null;
        }
      },
      error => this.msgSrv.error('基本类型键列表加载失败！', error.message)
    );
  }

  /**
   * 改变选中的基本类型键
   * @param baseTypeKey 基本类型键名
   */
  public changeKey(key: any): void {
    if (this.params.key !== key) {
      this.params.key = key;
      const apiValues = `/api/base-type-keys/${key.baseTypeKey}/base-type-values`;
      this.config.valuesLoading = true;
      this.apiSrv.get(apiValues).subscribe(
        data => {
          data.sort((a: any, b: any) => a.sequence - b.sequence);
          this.data.values = data;
          this.config.valuesLoading = false;
        },
        error => this.msgSrv.error('基本类型值加载失败！', error.message)
      );
    }
  }

  /**
   * 创建基本类型键
   */
  public createkey(): void {
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '创建基本类型键',
      nzContent: EditBaseTypeKeysComponent,
      nzWidth: 576,
      nzMaskClosable: false,
      nzOnOk: (component: EditBaseTypeKeysComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            this.data.keys = [...this.data.keys, data];
            this.msgSrv.success('创建基本类型键成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('创建基本类型键失败！', error.message);
            ref.getInstance().nzOkLoading = false;
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 修改基本类型键
   * @param key 基本类型键对象
   * @param event 点击事件对象
   */
  public updateKey(key: any, event: Event): void {
    event.stopPropagation();
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '修改基本类型键',
      nzContent: EditBaseTypeKeysComponent,
      nzComponentParams: { data: key },
      nzWidth: 576,
      nzMaskClosable: false,
      nzOnOk: (component: EditBaseTypeKeysComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            const index: number = this.data.keys.findIndex(item => item.id === key.id),
              keys: any[] = [...this.data.keys];
            keys[index] = data;
            this.data.keys = keys;
            this.msgSrv.success('修改基本类型键成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('修改基本类型键失败！', error.message);
            ref.getInstance().nzOkLoading = false;
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 删除基本类型键
   * @param key 基本类型键对象
   */
  public deleteKey(key: any): void {
    const deleteKey: string = `/api/base-type-keys/${key.id}`;
    this.apiSrv.delete(deleteKey).subscribe(
      () => {
        this.data.keys = this.data.keys.filter(item => item !== key);
        this.msgSrv.success('删除成功！', null);
      },
      error => this.msgSrv.error('删除失败！', error.message)
    );
  }

  /**
   * 创建基本类型值
   * @param event 点击事件对象
   */
  public createValue(event: Event): void {
    event.stopPropagation();
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '创建基本类型值',
      nzContent: EditBaseTypeValuesComponent,
      nzComponentParams: { key: this.params.key },
      nzWidth: 576,
      nzMaskClosable: false,
      nzOnOk: (component: EditBaseTypeValuesComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            const values = [...this.data.values, data];
            values.sort((a: any, b: any) => a.sequence - b.sequence);
            this.data.values = values;
            this.msgSrv.success('创建基本类型值成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('创建基本类型值失败！', error.message);
            ref.getInstance().nzOkLoading = false;
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 修改基本类型值
   * @param value 基本类型值对象
   */
  public updateValue(value: any): void {
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '修改基本类型值',
      nzContent: EditBaseTypeValuesComponent,
      nzComponentParams: { key: this.params.key, value: value },
      nzWidth: 576,
      nzMaskClosable: false,
      nzOnOk: (component: EditBaseTypeValuesComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            const index: number = this.data.values.findIndex(item => item.id === value.id),
              values: any[] = [...this.data.values];
            values[index] = data;
            this.data.values = values;
            this.msgSrv.success('修改基本类型值成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('修改基本类型值失败！', error.message);
            ref.getInstance().nzOkLoading = false;
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 删除基本类型值
   * @param value 基本类型值对象
   */
  public deleteValue(value: any): void {
    const deleteValue: string = `/api/base-type-values/${value.id}`;
    this.apiSrv.delete(deleteValue).subscribe(
      () => {
        this.data.values = this.data.values.filter(item => item !== value);
        this.msgSrv.success('基本类型值删除成功！', null);
      },
      error => this.msgSrv.error('基本类型值删除失败！', error.message)
    );
  }

  /**
   * 防抖动加载基本类型键
   */
  public debounceLoad(): void {
    clearTimeout(this.debounce);
    this.debounce = setTimeout(() => this.load(), 500);
  }

}
